// 封装 axios 实例
import axios from "axios";
// import axiosAdapterUniapp from 'axios-adapter-uniapp'
import { UniAdapter } from "uniapp-axios-adapter";
// import router from "@/router/index";
const instance = axios.create({
  // #ifdef H5
  baseURL: "/api", // 设置基础 URL
  // #endif
  // #ifndef H5
  baseURL: "http://192.168.101.6:8089", // 设置基础 URL
  // #endif
  // baseURL: "/api", // 设置基础 URL
  timeout: 5000, // 设置请求超时时间
  adapter: UniAdapter,
});
import { useTokenStore } from "@/stores/token.js";
// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    // 在发送请求之前做
    const userStore = useTokenStore();
    // //些什么，比如添加 token
    const token = userStore.getToken();
    console.log("header token:", token);
    config.headers.Authorization = token;
    return config;
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);
// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    if (response.data.code == 1) {
      uni.showToast({
        title: response.data.message,
        icon: "none",
        duration: 1500,
      });
    }
    return response.data;
  },
  (error) => {
    const errorMsg = error.response?.data?.message || "请求失败，请稍后再试";
    uni.showToast({
      title: errorMsg,
      icon: "none",
      duration: 2000,
    });
    const userStore = useTokenStore();
    // userStore.removeToken()
    // userStore.removeUserId()
    return Promise.reject(error);
  }
);

export default instance;
